<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\SystemUploadfile;
use app\common\controller\AdminController;
use app\common\service\MenuService;
use EasyAdmin\upload\Uploadfile;
use think\db\Query;
use think\facade\Cache;
use think\facade\Db;
use app\admin\model\Goods;
use app\admin\model\ManagementStore;
use function GuzzleHttp\json_decode;
use app\admin\model\ManagementStoreProductValue;
class Ajax extends AdminController
{

    /**
     * 初始化后台接口地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function initAdmin()
    {
        $cacheData = Cache::get('initAdmin_' . session('admin.id'));
        if (!empty($cacheData)) {
            return json($cacheData);
        }
        $menuService = new MenuService(session('admin.id'));
        $data = [
            'logoInfo' => [
                'title' => sysconfig('site', 'logo_title'),
                'image' => sysconfig('site', 'logo_image'),
                'href'  => __url('index/index'),
            ],
            'homeInfo' => $menuService->getHomeInfo(),
            'menuInfo' => $menuService->getMenuTree(),
        ];
        Cache::tag('initAdmin')->set('initAdmin_' . session('admin.id'), $data);
        return json($data);
    }

    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        $this->success('清理缓存成功');
    }

    /**
     * 上传文件
     */
    public function upload()
    {  
        
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('file'),
        ];
      
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
  
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $this->success($upload['msg'], ['url' => $upload['url']]);
        } else {
            $this->error($upload['msg']);
        }
    }
    //图片删除
    public function delImg(){
        $url=$this->request->get();
        
        del_image($url['url']);
        $this->success('删除成功');
    }
    /**
     * 上传图片至编辑器
     * @return \think\response\Json
     */
    public function uploadEditor()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('upload'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error'    => [
                    'message' => '上传成功',
                    'number'  => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url'      => $upload['url'],
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $this->model = new SystemUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }
    //获取商品
    public function getStoreProduct(){
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $where=[];
        if(isset($get['title']) && !empty($get['title'])){
            $where[]=['products_title','like','%'.$title.'%'];
        }
        $Goods= new Goods();
        $prvalue=new ManagementStoreProductValue();
        if(isset($get['area_id'])){
            $store=new ManagementStore();
            $storeIds=$store->where('area_id',$get['area_id'])->column('store_id');
            $count=$Goods->whereIn('store_id',$storeIds)->where($where)->count();
             $list =$Goods->with(['store'])->field('products_id,products_title,store_id,create_time,cate_id')
                ->whereIn('store_id',$storeIds)
                ->where($where)
                ->page($page, $limit)
                ->order('create_time desc')
                ->select()->bindAttr('store', ['shop_name' => 'store_name']);
        }else{
            $store_id=$get['store_id'];
            
            if(is_array($get['cate_id'])){
                $cate_id=$get['cate_id'];
            }else{
                $cate_id=json_decode($get['cate_id'],true);
            }
            $store_category_id=Db::name('store_category_server')->whereIn('server_id',$cate_id)->column('cate_id');
            if($store_category_id){
                $cate_id=$store_category_id;
            }
            $count=$Goods
            // ->whereIn('store_id',$store_id)
            ->whereIn('cate_id',$cate_id)->where($where)->count();
            $list =$Goods->with(['store'])->field('products_id,products_title,store_id,create_time,cate_id')
                // ->whereIn('store_id',$store_id)
                ->whereIn('cate_id',$cate_id)
                ->where($where)
                ->page($page, $limit)
                ->order('create_time desc')
                ->select()->bindAttr('store', ['shop_name' => 'store_name']);
        }
        
        foreach ($list as $k => $v) {
            $list[$k]['childern']=$prvalue->field('sku,products_id')->whereNotNull('sku')->where('products_id',$v['products_id'])->select();
        }
       
        
   
        if(isset($get['products_id']) && !empty($get['products_id'])){
            $package=json_decode(htmlspecialchars_decode($get['products_id']),true);
            if(is_array($package)){
                $productIds=array_column($package,'products_id');
                foreach ($list as $k => $v) {
                        if(in_array($v['products_id'],$productIds)){
                            $list[$k]['LAY_CHECKED']=true;
                        }else{
                            $list[$k]['LAY_CHECKED']=false;
                        }
                }
            }else{
               
                foreach ($list as $k => $v) {
                        if($v['products_id']==$package){
                            $list[$k]['LAY_CHECKED']=true;
                        }else{
                            $list[$k]['LAY_CHECKED']=false;
                        }
                }
            }
            
        }
        $data = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }
    public function getStore()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $list = Db::name('store') -> page($page,$limit) -> select()->toArray();
        $count = Db::name('store') -> count();
        $chargeGiftId = isset($get['chargeGiftId']) && $get['chargeGiftId'] > 0 ? $get['chargeGiftId'] : 0;
        $store_id = $get['store_id'];
        $this->model = new SystemUploadfile();
        $count = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->count();
        $list = $this->model
            ->where(function (Query $query) use ($title) {
                !empty($title) && $query->where('original_name', 'like', "%{$title}%");
            })
            ->page($page, $limit)
            ->order($this->sort)
            ->select();
        foreach ($list as $key => $value) {
            $exist = Db::name('send_product') -> where(['charge_gift_id' => $chargeGiftId,'product_id' => $value['store_id'] ]) -> findOrEmpty();
            if(count($exist) > 0){
                $list[$key]['LAY_CHECKED'] = true;
            }else{
                $list[$key]['LAY_CHECKED'] = false;
            }
            
        }
        $data = [
            'code'  => 0,
            'msg'   => $chargeGiftId,
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

}